package com.example.teach.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatClient;
    private final ChatMemory chatMemory;

    /**
     * 流式调用，支持对话记忆
     * @param prompt 用户输入的提示词
     * @param conversationId 对话ID，用于区分不同的对话
     * @return 流式响应
     */
    @RequestMapping(value = "/chat", produces = "text/html;charset=UTF-8")
    public Flux<String> chat(
            @RequestParam(defaultValue = "自我介绍一下") String prompt,
            @RequestParam(defaultValue = "default-conversation") String conversationId) {

        // 在Spring AI 1.0.0-M6版本中，通过prompt参数直接传入用户输入
        // 对话记忆由MessageChatMemoryAdvisor自动管理
        return chatClient
                .prompt(prompt)
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, conversationId))
                .stream() // 流式调用
                .content();
    }

    /**
     * 清除指定对话的历史记录
     * @param conversationId 对话ID
     */
    @RequestMapping("/clear-history")
    public void clearHistory(@RequestParam(defaultValue = "default-conversation") String conversationId) {
        chatMemory.clear(conversationId);
    }
}